package com.karaoke.android.library.utils

import java.io.BufferedReader
import java.io.DataOutputStream
import java.io.IOException
import java.io.InputStreamReader
import java.nio.charset.Charset

/**
 * Created by allen on 2017/4/28.
 */

object SilentInstall
{
    fun install(apkPath: String?): Boolean
    {
        if (apkPath == null) return false
        var result = false
        var dataOutputStream: DataOutputStream? = null
        var errorStream: BufferedReader? = null
        try
        {
            // 申请su权限
            val process = Runtime.getRuntime().exec("su")
            dataOutputStream = DataOutputStream(process.outputStream)
            // 执行pm install命令
            val command = "pm install -r $apkPath && am start -n com.karaoke.android.app/com.karaoke.android.app.MainActivity -a android.intent.action.MAIN -c android.intent.category.LAUNCHER \n"
            dataOutputStream.write(command.toByteArray(Charset.forName("utf-8")))
            dataOutputStream.flush()
            dataOutputStream.writeBytes("exit\n")
            dataOutputStream.flush()
            process.waitFor()
            errorStream = BufferedReader(InputStreamReader(process.errorStream))
            val msg = errorStream.readText()
            if (!msg.contains("Failure"))
            {
                result = true
            }
        }
        catch (e: Exception)
        {
        }
        finally
        {
            try
            {
                if (dataOutputStream != null)
                {
                    dataOutputStream.close()
                }
                if (errorStream != null)
                {
                    errorStream.close()
                }
            }
            catch (e: IOException)
            {
            }

        }
        return result
    }

    fun readLine(reader: BufferedReader): String?
    {
        return reader.readLine()
    }
}
